package com.zr.gdms.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zr.gdms.model.User;
import com.zr.gdms.service.LogService;
import com.zr.gdms.service.LoginService;
import com.zr.gdms.serviceimpl.LogServiceImpl;
import com.zr.gdms.serviceimpl.LoginServiceImpl;
import com.zr.gdms.util.NowDateUtil;
/**
 * 登录控制层
 * @author 李培宁
 *
 */
public class LoginControllerLPN extends HttpServlet{

	LoginService ls = new LoginServiceImpl();
	LogService log = new LogServiceImpl();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf8");
		resp.setCharacterEncoding("utf8");
		HttpSession session = req.getSession();
		PrintWriter pw = resp.getWriter();
		String uname = req.getParameter("uname");
		String upsw = req.getParameter("upsw");

		String rm = req.getParameter("rm");
		//记住密码
		if ("on".equals(rm)) {
			Cookie cuname = new Cookie("uname", uname);
			cuname.setMaxAge(60*60);
			Cookie cupsw = new Cookie("upsw", upsw);
			cupsw.setMaxAge(60*60);		
			resp.addCookie(cuname);
			resp.addCookie(cupsw);
		}
		User u = ls.findUserByUnameAndUpsw(uname, upsw);
		int uid = u.getUid();
		String ltime = NowDateUtil.nowDate();
		boolean flag = log.insertLog(uid, uname, ltime);

		if (u.getUid()>0) {
			session.setAttribute("user", u);			
			pw.write("1");
		} else {
			pw.write("0");
		}		
	}
}
